/*
 * @Author: Islands 1430536748@qq.com
 * @Date: 2024-07-13 16:41:31
 * @LastEditors: 周洋 1430536748@qq.com
 * @LastEditTime: 2024-08-04 00:49:09
 * @version: 1.0.0
 * @Description: axios
 */
import axios from "axios";
import { storeToRefs } from "pinia";
import { useLoading } from '@/hooks/index';
import { authorizeStore } from '../../plugins/pinia/index'

/** 请求配置 */
let requestNum = 0
export const service = (config: any) => {
    requestNum++;
    const { startLoading, endLoading } = useLoading()
    //1.请求初始化
    const instance = axios.create({
        baseURL: '/api',
        timeout: 5000,
        headers: {
            "Content-Type": "application/json;charset=utf-8",
        }
    });

    //2.请求拦截器
    instance.interceptors.request.use(function (config: any) {
        startLoading();
        // const { accountToken } = storeToRefs(authorizeStore());
        // if (accountToken.value === '') {
        //     router.push('/401')
        // } else {
        //     config.headers = accountToken;
        // }
        return config;
    }, function (error) {
        requestNum = 0
        endLoading()
        return Promise.reject(error);
    });


    //3.响应拦截器->获取后台数据前拦截
    instance.interceptors.response.use(function (response) {
        requestNum--;
        if (requestNum <= 0) {
            requestNum = 0
            endLoading();
        }
        return response.data;
    }, function (error) {
        endLoading();
        requestNum = 0
        console.log("error:" + error);
    });

    //发送一个真实的请求
    return instance(config);
}

//请求方法
export const doHttp = (method: string, url: string, params: any) => {
    return new Promise((resolve, reject) => {
        let promise: any
        if (method.toUpperCase() === 'GET') {
            promise = service({
                url,
                params
            })
        } else if (method.toUpperCase() === 'POST' || method.toUpperCase() === 'PATH') {
            promise = service({
                method: method,
                url,
                data: params
            })
        } else if (method.toUpperCase() === 'DEL') {
            promise = service({
                method: method,
                url,
                data: params
            })
        }
        //处理返回
        promise.then((res: any) => {
            resolve(res)
        }).catch((err: any) => {
            reject(err)
        })
    })
}

export const doGet = (url: string, params: any) => {
    return doHttp('get', url, params);
}
export const doPost = (url: string, params: any) => {
    return doHttp('post', url, params);
}
export const doDelete = (url: string, params: any) => {
    return doHttp('delete', url, params);
}
export const doPath = (url: string, params: any) => {
    return doHttp('path', url, params);
}
export const doPut = (url: string, params: any) => {
    return doHttp('put', url, params);
}